<?php
namespace app\manage\controller;

use think\Controller;
use think\Db;

class Init extends Controller
{
    public function _initialize(){
        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
        header('Access-Control-Allow-Methods: GET, POST, PUT');
        // 登录验证
        if(is_null(session('admin'))){
           $this->redirect('index/logpage');
        }

    }

    public function index()
    {
        // 页面信息
        $pageData = ['title'=>'设置初始用户'];

        $this->assign('pageData',$pageData);
        return view();
    }

    public function init_user(){
        $memberModel = new \app\common\model\Member;
        if($memberModel->count()){
            $this->error('系统前台已经存在会员，无法初始化');
        }

        $params = input('post.');
        $mid = $params['mid'];
        $password = $params['password'];

        $member = [
            'mid'=>$mid,
            'status'=>1, // 状态可用
            'type'=>2, // 实单
            'mname'=>'系统顶级会员',
            'password'=>hashPwd($password),
            'init_level'=>1,
            'level_id'=>1,
            'is_agent'=>1, // 是代理中心
            'agent_type_id'=>1, // 默认代理类型
        ];
        // 清空表
        $prefix = config('database.prefix');
        Db::query(" truncate table `".$prefix."member`");
        // 添加用户
        $memberModel->allowField(true)->save($member);
        $uid = $memberModel->getLastInsID();
        // 初始化账户
        $this->initAccount($uid);
        // 记录顶级用户MID
        model('option')->addOneData('init_uid',$uid);
        $CACHE = \app\common\cache\CacheData::getInstance('Option');
        $CACHE->updateCache();
        $this->redirect('main/index');
    }

    private function initAccount($uid){
        $coinData = model('coin')::coinData();
        // 所有货币类型金额初始化为100000
        $defaultAccount = [];
        foreach($coinData as $coin):
            $defaultAccount[] = [
                'uid' => $uid,
                'coin_id' => $coin['id'],
                'amount' => 1000000,
            ];
        endforeach;
        model('member_coin')->saveAll($defaultAccount);

        // 初始化AB大区剩余业绩，都为0
        $defaultAreaScore = [
            ['uid'=>$uid,'area'=>1,'score'=>0],
            ['uid'=>$uid,'area'=>2,'score'=>0]
        ];
        model('member_area_score')->saveAll($defaultAreaScore);

    }

}
